<template>
  <!-- 承诺卡管理 -->
  <div class="commitcard">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >
        <!-- 左上方菜单内容 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.promisecard_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport">
            批量导出
          </el-button>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="fj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['fj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
        </template>

        <!-- 附件表单自定义 -->
        <template slot="fjForm">
          <div>
            <el-upload
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="fjFileList"
              :before-upload="beforeUploadFJ"
              :on-remove="handleRemoveFJ"
              :on-success="uploadFJSuccess"
            >
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/saferisk/commitcard";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        viewBtn: true,
        selection: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        column: [
          {
            label: "承诺卡编号",
            prop: "cnkbh",
            align: "center",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入承诺卡编号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "承诺人",
            prop: "cnr",
            align: "center",
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id"
            },
            rules: [
              {
                required: true,
                message: "请选择承诺人",
                trigger: "change"
              }
            ]
          },
          {
            label: "主管领导",
            prop: "zgld",
            align: "center",
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id"
            },
            rules: [
              {
                required: true,
                message: "请选择主管领导",
                trigger: "change"
              }
            ]
          },
          {
            label: "岗位名称",
            prop: "gwmc",
            align: "center",
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/post/select?tenantId=" + tenantId,
            props: {
              label: "postName",
              value: "id"
            },
            rules: [
              {
                required: true,
                message: "请选择岗位名称",
                trigger: "change"
              }
            ]
          },
          {
            label: "承诺事项",
            prop: "cnsx",
            hide: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入承诺事项",
                trigger: "blur"
              }
            ]
          },
          {
            label: "承诺日期",
            prop: "cnrq",
            align: "center",
            type: "date",
            rules: [
              {
                required: true,
                message: "请选择承诺日期",
                trigger: "blur"
              }
            ]
          },
          {
            label: "附件",
            prop: "fj",
            align: "center",
            slot: true,
            formslot: true,
            viewDisplay: false,
            rules: [
              {
                required: true,
                message: "请选择附件",
                trigger: "blur"
              }
            ]
          }
        ]
      },
      // 附件
      fjFileList: [],
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 承诺卡按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.promisecard_add, false),
        viewBtn: this.vaildData(this.permission.promisecard_view, false),
        delBtn: this.vaildData(this.permission.promisecard_delete, false),
        editBtn: this.vaildData(this.permission.promisecard_edit, false)
      };
    },

    // 承诺卡列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 批量导出
    handleExport() {
      this.$confirm("是否批量导出承诺卡?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let cnkbh =
          this.query.cnkbh === undefined || this.query.cnkbh === null
            ? ""
            : this.query.cnkbh;
        let gwmc =
          this.query.gwmc === undefined || this.query.gwmc === null
            ? ""
            : this.query.gwmc;
        window.open(
          `/api/twoSinglesAndThreeCards/promisecard/export?${
            this.website.tokenHeader
          }=${getToken()}&cnkbh=${cnkbh}&gwmc=${gwmc}`
        );
      });
    },

    // 新增
    rowSave(row, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.cnrq =
        row.cnrq !== "" &&
        row.cnrq !== undefined &&
        typeof row.cnrq !== "string"
          ? this.formatAssessTime(row.cnrq)
          : "";
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 获取评估时间
    formatAssessTime(date) {
      var year = date.getFullYear();
      var month = this.getFullNum(date.getMonth() + 1);
      var day = this.getFullNum(date.getDate());
      return year + "-" + month + "-" + day;
    },

    // 补全时间
    getFullNum(num) {
      if (num < 10) {
        return "0" + num;
      }
      return num;
    },

    // 编辑
    rowUpdate(row, index, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.cnrq =
        row.cnrq !== "" &&
        row.cnrq !== undefined &&
        typeof row.cnrq !== "string"
          ? this.formatAssessTime(row.cnrq)
          : "";
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看、新增、编辑弹窗前
    beforeOpen(done, type) {
      this.fjFileList = [];
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (type === "edit") {
            this.fjFileList.push({
              name: this.form.bladeFile.fileName,
              response: {
                code: 200,
                success: true,
                msg: "操作成功",
                data: this.form.bladeFile
              }
            });
          }
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    // 格式化附件ID
    formatFJ(fileList) {
      var ids = [];
      fileList.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    }
    
  }
};
</script>

<style lang="scss" scpoed>
.commitcard {
  .avue-crud {
    .avue-crud__search {
      .avue-form__row:nth-child(1) {
        .el-form-item__label {
          text-align: unset;
          width: 90px !important;
        }

        .el-form-item__content {
          margin-left: 90px !important;
        }
      }
    }
  }

  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.avue-dialog {
  .el-dialog {
    .avue-group {
      .avue-form__group {
        .el-form-item {
          .el-form-item__label {
            width: 95px !important;
          }

          .el-form-item__content {
            margin-left: 95px !important;
          }
        }
      }
    }
  }
}
</style>